using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Api.DTO.WarehouseDto;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 获取入库单列表处理器
    /// </summary>
    public class GetStockInOrderHandler : IRequestHandler<GetStockInOrderCommand, ApiPaging<StockInOrderDto>>
    {
        private readonly IBaseRespository<StockInOrder> _stockInOrderRepository;
        private readonly IMapper _mapper;

        public GetStockInOrderHandler(IBaseRespository<StockInOrder> stockInOrderRepository, IMapper mapper)
        {
            _stockInOrderRepository = stockInOrderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取入库单列表请求
        /// </summary>
        /// <param name="request">获取入库单列表命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>入库单列表结果</returns>
        public async Task<ApiPaging<StockInOrderDto>> Handle(GetStockInOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<StockInOrderDto>();

            try
            {
                // 获取基础查询（排除已删除的数据）
                var stockInOrders = await _stockInOrderRepository.GetAllAsync();
                var query = stockInOrders.Where(o => !o.Isdel);

                // 应用查询条件
                if (!string.IsNullOrEmpty(request.OrderNumber))
                {
                    query = query.Where(o => o.OrderNumber.Contains(request.OrderNumber));
                }

                if (request.InType.HasValue)
                {
                    query = query.Where(o => o.InType == request.InType);
                }

                if (request.Status.HasValue)
                {
                    query = query.Where(o => o.Status == request.Status.Value);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(o => o.ActualInDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(o => o.ActualInDate <= request.EndDate.Value);
                }

                if (!string.IsNullOrEmpty(request.SupplierName))
                {
                    query = query.Where(o => o.SupplierName.Contains(request.SupplierName));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = _mapper.Map<List<StockInOrderDto>>(pagedData);
                }
                else
                {
                    result.PageDatas = new List<StockInOrderDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "仓库查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<StockInOrderDto>();
            }

            return result;
        }
    }
}